const app = getApp()
import {
  HomeIndex
} from 'index-modal.js';
import {
  Config
} from '../../../utils/config.js';
var Function = require("../../../utils/function.js");
var index = new HomeIndex(); //实例化 首页 对象
let time='';

Page({
  data: {
    youhuiflag: false,
    islog: false,
    islog_ed: false, //地理位子授权
    yy: false,
    imgUrls: [
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
    ],
    url: Config.Url,
    cityIndex: 0, //城市区域选中的index 用来分别
    active_endIndex: 0,
    type_id: '', //区域id
    jingdu: '', //经度
    weidu: '', //纬度
    pagesize: 1, //分页
    count:1, //优惠券
    indicatorDots: false,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    windowWidth: 0,
    indicatorColor: "#ccc",
    indicatorActiveColor: "#fff",
    list: [],
    page: 1,
    city: '',
    area: '',
    allCity:['广州市','白云区'],  
    // sonArea:[],
    is_show: false,
    is_search: false,
    tempCity: '',
    tipnotice: 1,
    lng: 0,
    lat: 0,
    showlist: [],
    isbooom: true,
    wOrder: '' //下拉是否能触底
  },
  link:function(e){
    let url = Function.getDataSet(e,'url');
    Function.linkTo(url);
  },
  onLoad: function(options) {

    var obj = wx.getLaunchOptionsSync()
    if(obj.query.doctor_id){
      wx.request({
        url: Config.restUrl+'weix/statisticsDoctorCode',
        user_id: wx.getStorageSync('members').id,
        method: 'POST',
        data: {
          doctor_id: obj.query.doctor_id,
        },
        header: {
          'content-type': 'application/json' // 默认
        },
      })
    }
    let that=this;
    this._getOrder()
    if (wx.getStorageSync('meny')) {
      this._getCountCity(() => {
        this._getgoodslist()
      })
    }

    if (wx.getStorageSync('members')) {
      this.setData({
        membersss: wx.getStorageSync('members')
      })
    }
    this._getBanner();
    this.config();
    // that._getCountCity(() => {
    //   that._getgoodslist()
    // })
    
    this.delrocrd()
  },
  

  //获取新人优惠券
  config: function() {
    let that = this;
    index.config((res) => {
      if (res.code == 200) {
        wx.setStorageSync('config', res.data);
        that.setData({
          config: res.data
        })
      }
    })
  },
  onHide:function(){
    // wx.offLocationChange(function(res){
    // })
    clearInterval(time);
  },

  onShow: function() {
    let that = this;
    let members = wx.getStorageSync('members') || [];
    if (Array.isArray(members)) {
      this.setData({
        // showlist:[]
      })
    } else {
      this.setData({
        youhuiflag: true,
      })
      time=setInterval(function(){
        that._getCountCity(() => {
          that._getgoodslist(1)
        })
      },1200)
    }

    

    setTimeout(function() {
      that._gethui();
    }, 1500)
  },

  // onReachBottom: function() {
  //   if (this.data.isbooom) {
  //     let page = this.data.page + 1;
  //     this.setData({
  //       page: page,
  //     })
  //     this.getList(this.data.city, this.data.area)
  //   }
  // },

  _getOrder(fn) {
    let that = this;
    let uid = wx.getStorageSync('members').id
    let meny = wx.getStorageSync('meny')
    let data = {
      uid,
      status: 3,
      jingdu: meny.weidu || '',
      weidu: meny.jingdu || ''
    }
    index.getOrder(data, (res) => {
      if (res.code == 200) {

        for (let i = 0; i < res.data.length; i++){
          let aa = res.data[i].status == 3 && res.data[i].pay_status == 1
          if (aa) {
            app.globalData.type = 2;
            app.globalData.activeindex = 2;
            wx.switchTab({
              url: '/pages/bill/noconsume/noconsume'
            })
          }
          else{
            return;
          }
        }
      }
    })
  },

  getList(city, area) {
    let that = this;
    let list = this.data.list;
    let lng = this.data.lng;
    let lat = this.data.lat;
  },
  getCity(pname) {
    this.setData({
      tempCity: pname
    });
    let all_city = this.data.allCity;
    for (let j in all_city) {
      if (j == pname) {
        this.setData({
          sonArea: all_city[j]
        });
      }
    }
  },
  findShop(e) { //选取城市
    let pname = parseInt(e.currentTarget.dataset.index);
    this.setData({
      cityIndex: pname
    })
    // this.getCity(pname);
  },
  searchShop(e) { //选取区域
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      active_endIndex: index,
      is_search: false,
      page: 1,
      isbooom: false,
      showlist: [],
      city: that.data.allCity[that.data.cityIndex].title + "-" + that.data.allCity[that.data.cityIndex]['_this'][that.data.active_endIndex].title,
      cityss: that.data.allCity[that.data.cityIndex].title
    })
    this._getgoodslist(1)
  },
  findAdd() {
    this.setData({
      is_search: true
    })
  },
  findMap() {
    let that = this;
    if (this.data.islog_ed) {
      that.setData({
        islog: true
      })
      setTimeout(() => {
        that.setData({
          islog: false
        })
      }, 2500)
    } else {
      wx.navigateTo({
        url: '/pages/shouye/ditu/ditu?jingdu=' + that.data.jingdu + "&weidu=" + that.data.weidu
      })
    }
  },
  close() {
    this.setData({
      tipnotice: 2
    })
    wx.setStorageSync('tipnotice', 2)
  },
  detail(e) {
    let that=this;
    let id = e.currentTarget.dataset.id;
    let status = e.currentTarget.dataset.status;
    let count = e.currentTarget.dataset.count; //是否优惠卷
    let formId = e.detail.formId;
    
    if (!wx.getStorageSync('members')) {
      wx.showModal({
        title: '提示',
        content: '你还未授权是否前往授权',
        
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/auth/auth',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      that.add_form(formId)
      wx.showModal({
        title: '温馨提示',
        content: '怀孕、体内有金属异物(包括钢板、钢钉等)、骨折及术后、出血性疾病、高热、皮肤感觉异常、恶性肿瘤、活动型肺结核、传染性疾病、严重心脑血管疾病、装有心脏起博器者不宜体验。\n 点击确定表示无上述不宜体验情况，并取号理疗。',
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/shouye/detail/detail?id=' + id
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
    }
    
  },
  // 收集formid
  add_form:function(formid){
    let that=this;
    let data={
      uid: wx.getStorageSync('members').id,
      form_id: formid
    }
    index.add_form(data,(res)=>{

    })
  },
  hideshade() {
    this.setData({
      is_search: false
    })
  },
  toUrl:function(){
    let that=this;
    wx.navigateTo({
      url: '/pages/my/member/member',
    })
  },
  _getCountCity(fun) { //获取门点区域
    let that = this;
    let data = {
      jingdu: wx.getStorageSync('meny').weidu,
      weidu: wx.getStorageSync('meny').jingdu,
    };
    index.getCountCity(data, (res) => {
      that.setData({
        allCity: res.data,
        pid: res.data[0].id
      })
      // that.getIndex(that.data.allCity)
      if (fun) {
        fun()
      }
    })
  },
  bindinput: function(e) {
    this.setData({
      titles: e.detail.value,
      page:1,
      showlist: []
    })
    this._getgoodslist(1);
  },
  _getgoodslist(type) {
    let that = this;
    var type_id;
    let data = {
      // type_id,

      jingdu: wx.getStorageSync('meny').weidu,
      weidu: wx.getStorageSync('meny').jingdu,
      page: that.data.page,
      uid: wx.getStorageSync('members').id
    }
    if (type == 1) {
      data.type_id = that.data.allCity[that.data.cityIndex]['_this'][that.data.active_endIndex].id;
    } else {
      data.type_id = '';
      data.pid =that.data.pid;
    }
    
    if (that.data.titles) {
      data.title = that.data.titles
    }
    
    index.getgoodslist(data, (res) => {
      if (res.code == 200 && res.data.length > 0) {
        if (res.data.length < 10) {
          that.setData({
            isbooom: false
          })
        }
        var showlist = this.data.showlist;
        var showlist_ed;
        if (showlist.length == 0 || res.data[0].id != showlist[0].id) {
          showlist_ed = showlist.concat(res.data)
        } else {
          showlist_ed = res.data
        }

        // for (let i = 0; i < res.data.length; i++) {
        //   if (res.data[i].bang == 1) {
        //     res.data[i].bangP = (Number(res.zhe) * (res.data[i].comp.price / 10)).toFixed(2)
        //   } else {
        //     res.data[i].bangP = 0
        //   }
        // }


        that.setData({
          showlist: showlist_ed,
          showlistss: res.data,
          city: that.data.allCity[that.data.cityIndex].title + "-" + that.data.allCity[that.data.cityIndex]['_this'][that.data.active_endIndex].title,
          cityss: that.data.allCity[that.data.cityIndex].title
        })
      } else {

      }
    })
  },
  // click:function(){
  //   let that=this;
  //   that.setData({
  //     count: that.data.youhuiflag ? that.data.showlist_ed.count : 2,
  //   })
  // },
  _gethui() {
    let that = this;
    let data = {
      uid: wx.getStorageSync('members').id
    }
    index.gethui(data, (res) => {
      if (res.msg == '您已领取新人优惠券') {
        that.setData({
          yy: true
        })
      }
      if (res.code == 200) {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
        that.setData({
          count: 2
        })
      } else {
        //  wx.showToast({
        //    title: res.msg,
        //    icon: 'none',
        //    duration: 1000
        //  })
      }
    })
  },
  penmap(e) {
    let lng = Number(e.currentTarget.dataset.lng);
    let lag = Number(e.currentTarget.dataset.lag);
    let adde = e.currentTarget.dataset.adde;
     
    wx.openLocation({
      latitude: lag,
      longitude: lng,
      name: adde,
      scale: 15,
      success: function() {
      }
    })
  },

  _gomap() {
    let that = this;
    let data = {

    }
  },

  _getBanner() {
    var that = this;
    index.getBanner((res) => {
      that.setData({
        imgUrls: res.data
      })
    })
  },

  postYoujui() { //点击使用优惠券
    // this._gethui();
    let that = this;
    that.setData({
      youhuiflag: false,
      count: 1
    })
    // that.onLoad();
  },


  delrocrd() {
    var that = this;

    wx.getLocation({
      type: 'gcj02',
      success: function (resdata) {
        let obj = {
          jingdu: resdata.latitude,
          weidu: resdata.longitude
        }
        wx.setStorage({
          key: 'meny',
          data: obj,
        })
        that.setData({
          jingdu: resdata.latitude,
          weidu: resdata.longitude
        })
        // that._getCountCity();
        that._getCountCity(() => {
          that._getgoodslist()
        })

      },
      fail() {
        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {

              wx.showModal({
                title: '',
                showCancel: false,
                content: '您未授权地理位置，部分功能将无法使用！',
                confirmText: '授权',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          that.setData({
                            islog_ed: true
                          })
                          wx.getLocation({
                            type: 'gcj02',
                            success(resdata) {
                              let obj = {
                                jingdu: resdata.latitude,
                                weidu: resdata.longitude
                              }
                              wx.setStorage({
                                key: 'meny',
                                data: obj,
                              })
                              that.setData({
                                jingdu: resdata.latitude,
                                weidu: resdata.longitude
                              })
                              // that._getCountCity();
                              that._getCountCity(() => {
                                that._getgoodslist()
                              })
                              if (fn) {
                                fn()
                              }
                            }
                          })
                        }
                      },
                    })
                  } 
                  else {
                    wx.showModal({
                      title: '',
                      showCancel:false,
                      content: '请在系统设置中打开定位服务',
                      confirmText: '确定',
                      success: function (res) {
                        fn()
                      }
                    })
                  }
                }
              })
            } else {
              wx.showModal({
                title: '',
                content: '请在系统设置中打开定位服务',
                confirmText: '确定',
                success: function (res) {
                  that.setData({
                    islog_ed: true
                  })
                }
              })
            }
          },
        })
      }
    })

    // wx.authorize({
    //   scope: 'scope.userLocation',
    //   success(res) {
        

        // wx.getLocation({
        //   type: 'wgs84',
        //   altitude: true, //高精度定位
        //   success: function(resdata) {
        //     let obj = {
        //       jingdu: resdata.latitude,
        //       weidu: resdata.longitude
        //     }
        //     wx.setStorage({
        //       key: 'meny',
        //       data: obj,
        //     })
        //     that.setData({
        //       jingdu: resdata.latitude,
        //       weidu: resdata.longitude
        //     })
        //     // that._getCountCity();
        //     that._getCountCity(() => {
        //       that._getgoodslist()
        //     })

        //   },
        // })
    //   },
    //   fail() {
    //     wx.showModal({
    //       title: '提示',
    //       content: '您未授权地理位置，功能将无法使用',
    //       showCancel: true,
    //       confirmText: "授权",
    //       confirmColor: "#52a2d8",
    //       success: function(res) {
    //         if (res.confirm) {
    //           //确认则打开设置页面（重点）
    //           wx.openSetting({
    //             success: (res) => {
    //               if (!res.authSetting['scope.userLocation']) {
    //                 //未设置录音授权
    //                 wx.showModal({
    //                   title: '提示',
    //                   content: '您未授权地理位置，功能将无法使用',
    //                   showCancel: false,
    //                   success: function(res) {
    //                     that.setData({
    //                       islog_ed: true
    //                     })
    //                   },
    //                 })
    //               } else {
    //                 //第二次才成功授权
    //                 wx.getLocation({
    //                   type: 'wgs84',
    //                   altitude: true, //高精度定位
    //                   success: function(resdata) {
    //                     let obj = {
    //                       jingdu: resdata.latitude,
    //                       weidu: resdata.longitude
    //                     }
    //                     wx.setStorage({
    //                       key: 'meny',
    //                       data: obj,
    //                     })
    //                     that.setData({
    //                       jingdu: resdata.latitude,
    //                       weidu: resdata.longitude,

    //                     })
    //                     that._getCountCity(() => {
    //                       that._getgoodslist()
    //                     })
    //                   },
    //                 })
    //               }
    //             },
    //             fail: function() {
    //               that.setData({
    //                 islog_ed: true
    //               })
    //             }
    //           })
    //         } else if (res.cancel) {
    //           that.setData({
    //             islog_ed: true
    //           })
    //         }
    //       },
    //       fail: function() {
    //         that.setData({
    //           islog_ed: true
    //         })
    //       }
    //     })
    //   }
    // })
  
  },
  onPullDownRefresh:function(){
    let that = this;
    that.setData({ page: 1, showlist: [], cityss: that.data.allCity[0].title, cityIndex: 0, active_endIndex:0})
    that._getCountCity(() => {
      this._getgoodslist()
    })
    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 2000)
  },
  onReachBottom: function () {
    let that = this;
    wx.showLoading({ title: '正在加载', mask: true })
    setTimeout(() => {
      that.data.page++;
      that._getgoodslist();
      wx.hideLoading()
    }, 1000)
  },
  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function () {
   
  }

})